using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace SettingsView.Search
{
	public class ExtractIcon
	{
		private struct SHFILEINFO
		{
			public IntPtr hIcon;

			public int iIcon;

			public uint dwAttributes;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
			public string szDisplayName;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
			public string szTypeName;

			public SHFILEINFO(bool b)
			{
				hIcon = IntPtr.Zero;
				iIcon = 0;
				dwAttributes = 0u;
				szDisplayName = "";
				szTypeName = "";
			}
		}

		private enum SHGFI
		{
			SHGFI_ICON = 256,
			SHGFI_DISPLAYNAME = 512,
			SHGFI_TYPENAME = 1024,
			SHGFI_ATTRIBUTES = 2048,
			SHGFI_ICONLOCATION = 4096,
			SHGFI_EXETYPE = 8192,
			SHGFI_SYSICONINDEX = 16384,
			SHGFI_LINKOVERLAY = 32768,
			SHGFI_SELECTED = 65536,
			SHGFI_ATTR_SPECIFIED = 131072,
			SHGFI_LARGEICON = 0,
			SHGFI_SMALLICON = 1,
			SHGFI_OPENICON = 2,
			SHGFI_SHELLICONSIZE = 4,
			SHGFI_PIDL = 8,
			SHGFI_USEFILEATTRIBUTES = 16
		}

		[DllImport("Shell32.dll")]
		private static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, out SHFILEINFO psfi, uint cbfileInfo, SHGFI uFlags);

		[DllImport("user32.dll", CharSet = CharSet.Auto)]
		private static extern bool DestroyIcon(IntPtr hIcon);

		public static ImageSource GetIcon(string strPath, bool selected, bool small)
		{
			SHFILEINFO psfi = new SHFILEINFO(true);
			int cbfileInfo = Marshal.SizeOf((object)psfi);
			SHGFI sHGFI = SHGFI.SHGFI_ICON;
			if (selected)
			{
				sHGFI |= SHGFI.SHGFI_OPENICON;
			}
			if (small)
			{
				sHGFI |= SHGFI.SHGFI_SMALLICON;
			}
			SHGetFileInfo(strPath, 256u, out psfi, (uint)cbfileInfo, sHGFI);
			if (psfi.hIcon != IntPtr.Zero)
			{
				Icon icon = Icon.FromHandle(psfi.hIcon);
				if (icon != null)
				{
					ImageSource result = Imaging.CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
					DestroyIcon(psfi.hIcon);
					return result;
				}
			}
			return null;
		}
	}
}
